package com.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author zhangs
 * @version v1.0
 * @decription Cookie 测试
 * @date 2021/3/23 22:16
 **/
@WebServlet(urlPatterns = "/demo05")
public class Demo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        boolean hasCookie = false;
        if (Objects.nonNull(cookies)) {
            for (Cookie cookie : cookies) {
                String name = URLDecoder.decode(cookie.getName(), "utf-8");
                if ("姓名".equals(name)) {
                    String value = URLDecoder.decode(cookie.getValue(), "utf-8");
                    hasCookie = true;
                    System.out.println(value);
                }
            }
        }

        String name = "姓名";
        String value = "李四";
        // 通过URLEncoder.encode()来进行编码
        name = URLEncoder.encode(name, "utf-8");
        value = URLEncoder.encode(value, "utf-8");
        // 创建Cookie对象
        Cookie cookie = new Cookie(name, value);
        // 设置cookie的生存事件
        cookie.setMaxAge(hasCookie ? 0 : -1);
        // 发送Cookie对象
        resp.addCookie(cookie);
    }
}
